<template>
  <div class="SecuritySetting">
    <div class="list-wrap">
      <div class="list-item">
        <div class="icon-wrap">
          <i class="iconfont icon-qitafuwu color-grey"></i>
        </div>
        <div class="info-wrap">
          <div class="info-title">
            <span>登录密码</span>
            <div class="status-tag green">已设置</div>
          </div>
          <div class="info-desc color-grey">
            <span>请设置包含字母、符号或数字中至少两项,长度超过6位的密码</span>
          </div>
        </div>
        <div class="btn-wrap">
          <el-button type="primary" size="medium" class="btn" @click="editPwd">修改</el-button>
        </div>
      </div>
      <div class="list-item">
        <div class="icon-wrap">
          <i class="iconfont icon-qitafuwu color-grey"></i>
        </div>
        <div class="info-wrap">
          <div class="info-title">
            <span>手机绑定</span>
            <div class="status-tag green">已设置</div>
          </div>
          <div class="info-desc color-grey">
            <span>已绑定手机<span class="color-primary">{{ userInfo.userPhoneNum }}</span>，可用于系统网页版、小程序登录、找回密码</span>
          </div>
        </div>
        <div class="btn-wrap">
          <el-button type="primary" size="medium" class="btn" @click="editMobile">修改</el-button>
        </div>
      </div>
    </div>

    <el-dialog title="修改密码" width="530px" :visible.sync="showPwdDialog" custom-class="my-dialog" :close-on-click-modal="false">
      <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" style="margin-top: -20px;" label-width="100px"
        size="medium" label-suffix=":">
        <!-- <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="pwdForm.oldPassword" placeholder="请输入旧密码" show-password />
        </el-form-item> -->
        <el-form-item label="">
           <span>当前绑定手机号:{{userInfo.userPhoneNum}}</span>
        </el-form-item>
        <el-form-item prop="code">
            <el-input v-model="pwdForm.code" placeholder="请输入图形验证码">
              <template #append>
                <img @click="getImgCaptcha" style="cursor: pointer;height:34px" :src="captchaObj?.img"  />
              </template>
            </el-input>
        </el-form-item>
        <el-form-item placeholder="请输入手机验证码" prop="smsCode">
            <el-input v-model="pwdForm.smsCode" placeholder="请输入手机验证码" autocomplete="off">
              <template #append>
                <el-button :disabled="countdown > 0" @click="getPwdSmsCode" >{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}</el-button>
              </template>
            </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="pwdForm.newPassword" placeholder="请输入新密码" show-password autocomplete="new-password" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="pwdForm.confirmPassword" placeholder="请再次输入新密码" show-password autocomplete="new-password" />
        </el-form-item>
      </el-form>
      <div slot="footer" style="margin-top: -30px;text-align: center;">
        <el-button :loading="confirmLoading" type="primary" @click="editPwdSubmit">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改绑定手机" width="740px" :visible.sync="showMobileDialog" custom-class="my-dialog" :close-on-click-modal="false">
      <el-steps :active="step" align-center finish-status="success" style="margin-top: -20px;">
        <el-step title="身份验证"></el-step>
        <el-step title="绑定新手机号"></el-step>
        <el-step title="申请成功"></el-step>
      </el-steps>

      <div v-if="step === 2" class="res-box">
        <i class="el-icon-success green"></i>
        <div class="res-text">手机绑定成功</div>        
      </div>
      <div class="form-wrap" v-else-if="step === 0">
        <span class="color-grey">当前绑定手机号：{{ userInfo.userPhoneNum }}</span>
        <el-form :model="mobileForm" :rules="mobileRules" ref="mobileFormRef" size="medium" style="margin-top: 20px;">
        <el-form-item prop="code">
            <el-input v-model="mobileForm.code" placeholder="请输入图形验证码">
              <template #append>
                <img @click="getImgCaptcha" style="cursor: pointer;height:34px" :src="captchaObj?.img"  />
              </template>
            </el-input>
        </el-form-item>
          <el-form-item prop="smsCode">
            <el-input v-model="mobileForm.smsCode">
                <template #append>
                  <el-button :disabled="countdown > 0" @click="getMobileSmsCode">{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}</el-button>
                </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-wrap" v-else-if="step === 1">
        <el-form :model="newMobileForm" :rules="newMobileRules" ref="newMobileFormRef" size="medium" style="margin-top: 20px;">
          <el-form-item prop="mobile">
            <el-input v-model="newMobileForm.mobile" placeholder="请输入新手机号码" />
          </el-form-item>
          <el-form-item prop="code">
              <el-input v-model="newMobileForm.code" placeholder="请输入图形验证码">
                <template #append>
                  <img @click="getImgCaptcha" style="cursor: pointer;height:34px" :src="captchaObj?.img"  />
                </template>
              </el-input>
          </el-form-item>
          <el-form-item prop="smsCode">
            <el-input v-model="newMobileForm.smsCode">
                <template #append>
                  <el-button :disabled="countdown > 0" @click="getSmsCode">{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}</el-button>
                </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" style="margin-top: -30px;text-align: center;">
        <el-button type="primary" style="min-width: 220px" @click="editMobileSubmit">下一步</el-button>
      </div>
    </el-dialog>
    <el-dialog title="请输入图形验证码确认" width="400px" :visible.sync="showPhoneDialog">
      <el-input v-model="imgcode" placeholder="请输入图形验证码">
        <template #append>
          <img @click="getPhoneCaptcha" style="cursor: pointer;height:34px" :src="phoneCaptchaObj?.img"  />
        </template>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPhoneDialog = false">取 消</el-button>
        <el-button :loading="confirmLoading" type="primary" @click="getSmsCode">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { changePassword, getcode, sendSmsCode,validateMobile,changeMobile,sendChangePasswordSmsCode, sendValidateMobileSmsCode} from '@/api/homeApi'
export default {
  data() {
    var validatePassword = (rule, value, callback) => {
        var reg = /^\S*(?=\S{8})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/;
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!reg.test(value)) {
          callback(new Error('密码长度8-20位，至少包含1个大写字母，1个小写字母，1个数字和一个特殊符号(!@#$%^&*?.)'));
        } else {
          callback();
        }
    };
    var validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.pwdForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      showPwdDialog: false,
      pwdForm: {
        code: '',
        smsCode: '',
        newPassword: '',
        newPasswordConfirm: ''
      },
      pwdRules: {
        code: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
        newPassword: [{ required: true, validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: 'blur' }]
      },
      showMobileDialog: false,
      mobileForm: {
        smsCode: '',
      },
      mobileRules: {
        code: [{ required: true, message: '请输入信息', trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入信息', trigger: 'blur' }],
      },
      newMobileForm: {
        mobile:'',
        code:'',
        smsCode: '',
        token: '',
        uuid: ''
      },
      newMobileRules: {
        mobile: [{ required: true, message: '请输入信息', trigger: 'blur' }],
        code: [{ required: true, message: '请输入信息', trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入信息', trigger: 'blur' }]
      },
      step: 0,
      captchaObj: {
        img: '',
        uuid: ''
      },
      phoneCaptchaObj: {
        img: '',
        uuid: ''
      },
      phoneScence: 1,
      showPhoneDialog: false,
      imgcode: '',
      confirmLoading: false,
      validToken: '',
      countdown: 0
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  methods: {
    editPwd() {
      this.showPwdDialog = true
       this.step = 0;
      this.getImgCaptcha()
    },
    editPwdSubmit() {
      this.$refs.pwdFormRef.validate((valid) => {
        if (valid) {
          this.pwdForm.uuid = this.captchaObj.uuid
          this.confirmLoading = true
          changePassword(this.pwdForm).then(res => {
            // this.$message.success('修改密码成功')
            if (res.code === 200) {
              this.$message.success('修改密码成功')
              this.showPwdDialog = false
            }else{
              this.getImgCaptcha()
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        } else {
          return false
        }
      })
    },
    // 获得默认账号密码登录的图形验证码
    getImgCaptcha() {
      getcode().then(res => {
        this.captchaObj.img = 'data:image/png;base64,' + res.img;
        this.captchaObj.uuid = res.uuid;
      });
    },
    // 设置密码时发送图形验证码
    getPwdSmsCode() {
      sendChangePasswordSmsCode().then(res => {
        if (res.code === 200) {
          this.$message.success('验证码发送成功！');
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }else{
          this.getImgCaptcha();
        }
      }).finally(() => {
      });
    },
    // 验证当前手机获取验证码
    getMobileSmsCode() {
      sendValidateMobileSmsCode().then(res => {
        if (res.code === 200) {
          this.$message.success('验证码发送成功！');
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }else{
          this.getImgCaptcha();
        }
      }).finally(() => {
      });
    },
    // 图形验证码确认发送短信验证码
    getSmsCode() {
      let mobile = this.step === 0 ? this.userInfo.userPhoneNum : this.newMobileForm.mobile
      let code = this.step === 0 ? this.pwdForm.code : this.newMobileForm.code
      this.phoneScence = this.step === 0 ? 4 : 5
      sendSmsCode({mobile:mobile,scene:this.phoneScence,code:code,uuid:this.captchaObj.uuid}).then(res => {
        if (res.code === 200) {
          this.$message.success('验证码发送成功！');
          this.showPhoneDialog = false;
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }else{
          this.getPhoneCaptcha();
        }
      }).finally(() => {
      });
    },
    editMobile() {
      this.showMobileDialog = true
      this.getImgCaptcha()
    },
    editMobileSubmit() {
      if(this.step === 0){
          this.mobileForm.uuid = this.captchaObj.uuid
          this.confirmLoading = true
          this.$refs.mobileFormRef.validate((valid) => {
            if (valid) {
              validateMobile(this.mobileForm).then(res => {
                if(res.code === 200){
                  this.newMobileForm.token = res.data.token
                  this.step = 1
                  this.getImgCaptcha();
                  this.countdown = 0
                } else {
                  this.getImgCaptcha();
                  this.countdown = 0
                }
              }).finally(() => {
                this.confirmLoading = false
              })
            }
          })
      }else if(this.step === 1){
        this.$refs.newMobileFormRef.validate((valid) => {
          if (valid) {
            this.confirmLoading = true
            this.newMobileForm.uuid = this.captchaObj.uuid
            changeMobile(this.newMobileForm).then(res => {
              if(res.code === 200){
                this.step = 2
              }else{
                this.getImgCaptcha();
                this.countdown = 0
              }
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            return false
          }
        })
      }
    }
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";
:deep(.el-form-item)  {
  margin-bottom: 30px;
}
:deep(.el-step__title.is-success) {
  color: $text-color;
}

:deep(.el-step__head.is-success) {
  color: $text-color-blue;
  border-color: $text-color-blue;
}

:deep(.el-step__title.is-process) {
  color: $text-color-blue !important;
}

:deep(.el-step__head.is-success .el-step__line-inner) {
  // transition-delay: 0ms;
  border-width: 1px !important;
  width: 100% !important;
}

:deep(.el-step__head.is-process) {
  color: $text-color-blue;
  border-color: $text-color-blue;
}

:deep(.el-step__title.is-process) {
  font-weight: 400;
  color: rgb(122, 121, 121);
}

:deep(.el-step__title.is-wait) {
  color: rgb(122, 121, 121);
}

.SecuritySetting {
  .list-wrap {
    padding: 30px;

    .list-item {
      display: flex;
      align-items: center;
      box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.16);

      &+.list-item {
        margin-top: 20px;
      }

      .icon-wrap {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 97px;

        &::after {
          content: '';
          position: absolute;
          right: 0;
          top: 10%;
          display: block;
          width: 1px;
          height: 80%;
          background-color: #E8E8E8;
        }

        i {
          font-size: 40px;
        }
      }

      .info-wrap {
        padding: 0 20px 0 30px;
        flex: 1;

        .info-title {
          margin-top: 15px;
          display: flex;
          align-items: center;
          font-size: 16px;
          font-weight: bold;

          .status-tag {
            margin-left: 30px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 63px;
            height: 27px;
            border-radius: 3px;
            font-size: 14px;
            font-weight: normal;

            &.green {
              color: $--color-success;
              background: rgba(3, 194, 153, 0.1);

            }

            &.orange {
              color: $--color-danger;
              background: rgba(250, 83, 48, 0.1);
            }

            &.blue {
              color: $--color-primary;
              background: rgba(67, 106, 247, 0.2)
            }
          }
        }

        .info-desc {
          margin-top: 14px;
          margin-bottom: 14px;
          font-size: 14px;
        }
      }

      .btn-wrap {
        padding-right: 30px;
      }
    }
  }

  .my-dialog {
    .form-wrap {
      padding: 30px 220px 0 108px;
    }

    .res-box {
      margin-bottom: 30px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      i {
        margin-top: 30px;
        font-size: 48px;

        &.green {
          color: $--color-success;
        }
      }

      .res-text {
        margin-top: 20px;
        font-size: 26px;
      }
    }
  }
}
</style>